<!--
 * @Author: panghu chenjh@datamargin.com
 * @Date: 2024-04-15 15:01:58
 * @LastEditors: panghu chenjh@datamargin.com
 * @LastEditTime: 2024-05-04 16:33:43
 * @FilePath: \zheye\src\views\createPost.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="login-page mx-auto p-3 w-330 create-post-page">
    <h3 class="my-4">{{ commitName === 'updatePost' ? '编辑文章' : '新建文章' }}</h3>
    <Uploader action="/api/upload"
      :beforeUpload="beforeUploadFn" @file-uploaded="fileUploaded" :isClear="isClear" @updateIsClear="isClear = false"
      :uploaded="uploadedData"
      class="d-flex align-items-center justify-content-center bg-light text-secondary w-100 my-4">
      <h2>点击上传头图</h2>
      <template #loading>
        <div class="d-flex">
          <div class="spinner-border text-secondary" role="status">
          </div>
          <h2>正在上传</h2>
        </div>
      </template>
      <template #uploaded="uploadedPops">
        <div class="position-relative" style="width: 100%; height: 100%;">
          <div class="uploaded-area" style="width: 100%; height: 100%;">
            <img :src="uploadedPops.uploadedData">
          </div>
          <div class="position-absolute" @click.stop style="width: 100%; height: 100%; left: 0; top: 0;">
            <button class="btn position-absolute" @click.stop="handleDeleteUploadedImg" style="font-size: 40px; left: 50%; top: 50%;transform: translate(-50%, -50%);">x</button>
          </div>
        </div>
      </template>
    </Uploader>
    <ValidateForm @form-submit="onSubmitForm">
      <div class="mb-3">
        <label class="form-label">标题</label>
        <ValidateInput v-model="formData.title" :rules="titleRules"/>
      </div>
      <div class="mb-3">
        <label class="form-label">内容</label>
        <ValidateInput v-model="formData.content" :rules="contentRules" tag="textarea" rows="10"/>
      </div>
      <template #submit>
        <button type="button" class="btn btn-primary">{{ commitName === 'updatePost' ? '提 交' : '创 建' }}</button>
      </template>
    </ValidateForm>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import ValidateInput, { RulesType } from '@/components/ValidateInput.vue'
import ValidateForm from '@/components/ValidateForm.vue'
import Uploader from '@/components/Uploader.vue'
import CreateMessage from '@/components/createMessage'
import { ResponseType, ImageProps, PostProps } from '@/store'
import { beforeUploadCheck } from '@/utils/helper'
export default defineComponent({
  name: 'CreatePost',
  components: { ValidateForm, ValidateInput, Uploader },
  setup () {
    const store = useStore()
    const router = useRouter()
    const route = useRoute()
    const isClear = ref(false)
    const uploadedData = ref('')
    const isEdit = !!route.query.id
    const commitName = ref(isEdit ? 'updatePost' : 'createPost')
    let imageResUrl: string | undefined = ''
    const titleRules: RulesType = [
      { type: 'required', message: '请输入标题' }
    ]
    const contentRules: RulesType = [
      { type: 'required', message: '请输入内容' }
    ]
    const formData = reactive({
      title: '',
      content: ''
    })
    onMounted(() => {
      if (isEdit) {
        store.dispatch('fetchPost', route.query.id).then(res => {
          console.log('res===', res.data)
          formData.title = res.data.title
          formData.content = res.data.excerpt || res.data.content || ''
          if (res.data.image && res.data.image.url) {
            uploadedData.value = res.data.image.url
            imageResUrl = res.data.image.url
          }
        })
      }
    })
    const onSubmitForm = () => {
      const { column, _id } = store.state.user
      if (column) {
        const newPost: PostProps = {
          title: formData.title,
          content: formData.content,
          column,
          author: _id
        }
        if (imageResUrl) {
          newPost.image = imageResUrl
        }
        let data: null | object = null
        if (isEdit) {
          data = {
            method: 'patch',
            data: {
              id: route.query.id,
              payload: newPost
            }
          }
        } else {
          data = newPost
        }
        store.dispatch(commitName.value, data).then(res => {
          CreateMessage(isEdit ? '文章编辑成功' : '文章新建成功', 'success')
          setTimeout(() => {
            router.push({
              name: 'postDetail',
              params: {
                id: res.data._id
              }
            })
          }, 2000)
        })
      }
    }
    const beforeUploadFn = (file: File) => {
      const { error, passed } = beforeUploadCheck(file, {
        format: ['image/png', 'image/jpeg', 'image/jpg'], // 'image/png'
        size: 1
      })
      if (error === 'size') {
        CreateMessage('请上传小于1M的图片', 'error')
        return false
      }
      if (error === 'format') {
        CreateMessage('请上传格式为【image/png, image/jpeg, image/jpg】的图片', 'error')
        return false
      }
      return true
    }
    const fileUploaded = (response: ResponseType<ImageProps>) => {
      if (response.data._id) {
        imageResUrl = response.data.url
        CreateMessage(response.data._id, 'success')
      }
    }
    const handleDeleteUploadedImg = () => {
      isClear.value = true
      imageResUrl = ''
      uploadedData.value = ''
    }
    return {
      titleRules,
      contentRules,
      formData,
      onSubmitForm,
      beforeUploadFn,
      fileUploaded,
      handleDeleteUploadedImg,
      isClear,
      uploadedData,
      commitName
    }
  }
})
</script>

<style>
.create-post-page .file-upload-container {
  height: 200px;
  cursor: pointer;
  overflow: hidden;
}
.create-post-page .file-upload-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.uploaded-area {
  position: relative;
}
.uploaded-area:hover h3 {
  display: block;
}
.uploaded-area h3 {
  display: none;
  position: absolute;
  color: #999;
  text-align: center;
  width: 100%;
  top: 50%;
}
</style>
